const readline = require('readline');

// node .\scripts\wallet.js
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('请输入密码:', (answer1) => {
    rl.question('确认密码:', (answer2) => {
        if (answer1 == answer2) {
            //console.log(`两次密码输入正确`);

            var ethers = require('ethers');
            let provider = ethers.getDefaultProvider();


            //生成的钱包信息
            var wallet = ethers.Wallet.createRandom();
            // console.log(wallet);

            //获取助记词
            var mnemonic = wallet.mnemonic;
            // console.log("钱包助记词：", mnemonic.phrase);

            //获取钱包地址
            var address = wallet.address;


            console.log("\n注册成功！！！");
            console.log("钱包地址：", address);

            var privateKey = wallet.privateKey;

            let walletWithProvider = new ethers.Wallet(privateKey, provider);

            // console.log(walletWithProvider);

            //---------------------------------------------------------------------------

            //密码进行传参
            // let password = 123;

            function callback(progress) {
                // console.log("Encrypting: " + parseInt(progress * 100) + "% complete");
            }

            let encryptPromise = wallet.encrypt(answer2, callback);

            encryptPromise.then(function (json) {


                var fs = require("fs");
                var data = json;
                var data1 = mnemonic.phrase;
                // var timestamp = new Date();

                // 创建一个可以写入的流，写入到文件 output.txt 中
                var writerStream = fs.createWriteStream('UTC--' + address + '.key');
                var writerStream1 = fs.createWriteStream('UTC--' + address + '.mnemonic');

                // 使用 utf8 编码写入数据
                writerStream.write(data, 'UTF8');
                writerStream1.write(data1, 'UTF8');

                // 标记文件末尾
                writerStream.end();
                writerStream1.end();

                // 处理流事件 --> data, end, and error
                writerStream.on('finish', function () {
                    console.log("json文件下载完成。");
                });
                writerStream1.on('finish', function () {
                    console.log("助记词文件下载完成。");
                });

                writerStream.on('error', function (err) {
                    console.log(err.stack);
                });

                writerStream1.on('error', function (err) {
                    console.log(err.stack);
                });
            })
        } else {
            console.log(`注册失败，确认密码出错`);
        }
        rl.close();
    });
});